package com.bestcem.xm.wallet.controller;

import com.bestcem.xm.common.core.constant.ReqErrorCodeConstants;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.wallet.controller.vo.request.RechargeOrderCallbackVO;
import com.bestcem.xm.wallet.enums.WalletRechargeOrderStatusEnum;
import com.bestcem.xm.wallet.service.LimitOrderService;
import com.bestcem.xm.wallet.service.dto.LimitOrderDTO;
import com.bestcem.xm.wallet.util.business.CheckSignUtil;
import com.bestcem.xm.wallet.util.convert.LimitOrderConvert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户企业钱包回调服务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/18 10:11
 */
@Slf4j
@AuthIgnore
@RestController
@RequestMapping(value = "/wallet/callback")
public class UserWalletCallbackController {

    @Resource
    private LimitOrderConvert limitOrderConvert;

    @Resource
    private LimitOrderService limitOrderService;

    @Resource
    private CheckSignUtil checkSignUtil;

    /**
     * 通知企业钱包充值订单状态回调接口
     *
     * @param orderCallbackVO 回调参数
     * @return XmResultJson<Void>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/5/18 10:11
     */
    @PostMapping("/recharge_order_callback")
    public XmResultJson<Void> rechargeOrderCallback(HttpServletRequest request,
                                                    @RequestBody RechargeOrderCallbackVO orderCallbackVO) {
        // 验签
        if (!checkSignUtil.checkWalletCallbackSign(request, orderCallbackVO)) {
            return XmResultJson.fail(ReqErrorCodeConstants.SIGN_ERROR, "签名异常");
        }
        // 设置参数
        LimitOrderDTO limitOrderDTO = limitOrderConvert.rechargeOrderCallbackVo2Dto(orderCallbackVO);
        limitOrderDTO.setStatus(WalletRechargeOrderStatusEnum.getByStatus(orderCallbackVO.getStatus()).getLimitOrderStatus());
        // 修改状态
        ServiceResult<Void> result = limitOrderService.rechargeOrderCallback(limitOrderDTO);
        // 处理失败
        if (!result.isSuccess()) {
            return XmResultJson.fail(Integer.valueOf(result.getErrorCode()), result.getMsg());
        }
        // 处理成功,设置返回值
        return XmResultJson.success();
    }

}
